package com.maxima.attendance.actions;

import org.apache.struts2.convention.annotation.InterceptorRef;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.google.gson.Gson;
import com.maxima.attendance.constants.Constants;
import com.maxima.attendance.daos.TimeLogDAO;
import com.maxima.attendance.daos.UserDAO;
import com.maxima.attendance.interceptors.SessionValidator;
import com.maxima.attendance.pojos.Employee;
import com.maxima.attendance.pojos.TimeLog;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CheckInCheckOutAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String password;
	private String jsonResponse = "";
	// for logging
	static Logger logger = Logger.getLogger(ProjectAction.class.getName());
	private UserDAO userDAO = new UserDAO();
	private TimeLogDAO timeLogDAO = new TimeLogDAO();
	private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

	@Override
	@Action(value = "showCheckInOut", results = {
	@Result(name = "user", type = "json"), @Result(name = "admin", type = "json"), @Result(name = "error", location = "index.jsp")
	}, interceptorRefs = {
		@InterceptorRef(value = "defaultInterceptorStack")
	})
	public String execute() throws Exception {
		Employee employee = new UserDAO().getEmployee(id);
		try {
			jsonResponse = new Gson().toJson(employee);
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return SUCCESS;
	}

	@Action(value = "checkIn", results = {
	@Result(name = "user", type = "json"), @Result(name = "admin", type = "json"), @Result(name = "error", type = "json")
	}, interceptorRefs = {
		@InterceptorRef(value = "defaultInterceptorStack")
	})
	public String checkIn() {
		try {
			login();
			return SUCCESS;
		}
		catch (Exception e) {
			logger.info(e.getMessage());
			return ERROR;
		}
	}

	private void login() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Employee employee = new UserDAO().getEmployee(id);
		validatePassword(employee, request.getParameter("password"));
		if (employee.getLoggedIn() || employee.getLoggedOut()) {
			jsonResponse = new Gson().toJson(addLogoutEntry(employee));
		} else if (employee.getAbsent()) {
			jsonResponse = new Gson().toJson(addLoginEntry(employee));
		}
	}

	private void validatePassword(Employee employee, String password) throws Exception {
		if (!employee.getPassword().equals(password)) {
			throw new Exception("Invalid Password");
		}
	}

	private Employee getSelectedProfile() {
		Employee selectedProfile = new UserDAO().getEmployee(id);
		return selectedProfile;
	}

	/*
	 * private void updateList(Employee employee) { InitializeList
	 * initializeList= new InitializeList(); List<Employee> employeeList =
	 * initializeList.getEmployeeList(); if (employeeList.contains(employee)) {
	 * int i = employeeList.indexOf(employee); employeeList.remove(i);
	 * employeeList.add(i, employee); }
	 * map.put(Constants.CURRENT_EMPLOYEE_LIST,employeeList); }
	 */
	public Employee addLoginEntry(Employee selectedProfile) {
		Date date = new Date();
		TimeLog timeLog = new TimeLog(date, selectedProfile.getId());
		timeLog.setLoginTime(date);
		timeLog.setComment("none");
		timeLogDAO.addNewTimeLog(timeLog);
		logger.info("Employee " + selectedProfile.getFirstName() + " Id - " + selectedProfile.getId() + " Logged In Successfully");
		selectedProfile.setTimeLog(timeLog);
		return selectedProfile;
	}

	private Employee addLogoutEntry(Employee selectedProfile) {
		Date date = new Date();
		TimeLog timeLog = timeLogDAO.addTimeOut(selectedProfile.getTimeLogId(), date);
		logger.info("Employee " + selectedProfile.getFirstName() + " Id - " + selectedProfile.getId() + " Logged Out Successfully");
		selectedProfile.setTimeLog(timeLog);
		return selectedProfile;
	}

	@Action(value = "changeUserPasswordByAdmin", results = {
	@Result(name = "admin", type = "json"), @Result(name = "error", type = "json"),
	}, interceptorRefs = {
		@InterceptorRef(value = "defaultInterceptorStack")
	})
	public String changeUserPassword() throws Exception {
		Employee employee = getSelectedProfile();
		try {
			validatePassword(employee, ServletActionContext.getRequest().getParameter("old_password"));
			userDAO.changePassword(employee.getId(), ServletActionContext.getRequest().getParameter("inputPassword"));
			logger.info("Employee " + employee.getFirstName() + " Id - " + employee.getId() + " changed his password Successfully");
		}
		catch (Exception e) {
			jsonResponse = new Gson().toJson("error");
			System.out.println(e.getMessage());
		}
		jsonResponse = new Gson().toJson("success");
		return SUCCESS;
	}

	@Action(value = "showChangeUserPasswordScreen", results = {
	@Result(name = "user", type = "tiles", location = "changeUserPasswordByUser.tiles"), @Result(name = "admin", type = "tiles", location = "changeUserPasswordByAdmin.tiles"), @Result(name = "error", location = "index.jsp")
	}, interceptorRefs = {
		@InterceptorRef(value = "defaultInterceptorStack")
	})
	public String checkLoginType() {
		return SessionValidator.validateSession();
	}

	public String getJsonResponse() {
		return jsonResponse;
	}

	public void setJsonResponse(String jsonResponse) {
		this.jsonResponse = jsonResponse;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
